import {Component, OnInit} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {environment} from '../../../../environments/environment';
import * as _ from 'underscore';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
  result = {
    list: [],
    count: 0,
    page: 1,
    size: 10,
    sort: []
  };

  constructor(
    private http: HttpClient,
    private message: NzMessageService
  ) {
  }

  ngOnInit(): void {
    this.load();
  }

  pageChange(pageNo) {
    this.result.page = pageNo;
    this.load();
  }

  private load() {
    this.http.get(environment.uri + '/project', {params: this.getParam()}).subscribe(res => {
      this.result.list = res[`content`];
      this.result.count = res[`totalElements`];
    });
  }

  private getParam() {
    let params = new HttpParams();
    params = params.append('page', String(this.result.page - 1));
    params = params.append('size', String(this.result.size));
    _.map(this.result.sort, o => {
      const sort = o.key + ',' + (o.value === 'ascend' ? 'asc' : 'desc');
      params = params.append('sort', sort);
    });
    return params;
  }

  sort($event: { key: string; value: string }) {
    if ($event.value === null) {
      this.result.sort = _.filter(this.result.sort, o => o.key !== $event.key);
    } else if (_.filter(this.result.sort, o => o.key === $event.key).length > 0) {
      this.result.sort = _.map(this.result.sort, o => {
        if (o.key === $event.key) {
          o = $event;
        }
        return o;
      });
    } else {
      this.result.sort.push($event);
    }
    this.load();
  }

  deleteConfirm(id) {
    this.http.delete(environment.uri + '/project/' + id).subscribe(() => {
      this.message.create('success', '删除成功');
      this.load();
    });
  }
}
